var express 		= require('express');
var mysql   		= require('mysql');
var config  		= require('../config.json');
var sqlconfig 		= config.mysql;
var router  		= express.Router();
var pool    		= mysql.createPool(sqlconfig);

/*
  Name: data
  Args:
	data:data to be return
	res :response to write data
  Return : 
	Valid String for Client to use
  Description：
	  Return the valid  Data String to client if there is no error
*/

function data(data,res)
{
	console.log("LOG:RESPONSE:"+JSON.stringify(data));
	return res.end(JSON.stringify({err:0,response:data}));
}

/*
  Name: error
  Args:
	res:response to write err
	err:error message to return
	errcode: description of an error
  Return : 
	Valid String for Client to use
  Description：
	Return the error message to the client 
*/

function error(err,errcode,res)
{
	console.log("LOG:ERROR:"+JSON.stringify(errcode));
	return res.end(JSON.stringify({err : err,errcode : errcode}));
}

/*
  Name: BeforeAspect 
  Args: 
	request:Object
  Return: 
	data return from this aspect
  Description:
	preprocessor
*/

function BeforeAspect(request)
{
	
	console.log("LOG:REQUEST:"+JSON.stringify(request));
	return request;
}


/*
  Name:Student_Check_Information 
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_id 		: student to add score
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    appear the basic information of a student
*/
function Student_Check_Information (req,res,next)
{
	var query = "SELECT s.stu_name, s.stu_number, class.class_name,class.grade FROM ( SELECT * FROM student WHERE stu_id = ?) s LEFT JOIN class ON s.class_id = class.class_id;";

	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'STUDENT')
		{
			error(402,"Login First",res);
			return;
		}
		
		var query_args = [];
		query_args.push(req.session.user['stu_id']);


		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
			}
			else if(rows.length == 1)
			{
				data(rows[0],res);
			}
			else
			{
				error(303,"No data avalible",res);					
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res)
	}
	return;
}

/*
  Name:Student_Modify_Password 
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_id 		: student to add score
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    modify the basic information of a student(password)
*/
function Student_Modify_Password (req,res,next)
{
	var query = "UPDATE student SET stu_password = ? WHERE stu_id = ? AND stu_password = ?;";
	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'STUDENT')
		{
			error(402,"Login First",res);
			return;
		}
		if(typeof(args['stu_old_password']) != 'string' 
		|| typeof(args['stu_config_password']) != 'string'
		|| typeof(args['stu_password']) != 'string' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}

		if(args['stu_password'] != args['stu_config_password'])
		{
			error(202,"Wrong config_password",res);
			return;
		}

		var query_args = [];
		query_args.push(args['stu_password']);
		query_args.push(req.session.user['stu_id']);
		query_args.push(args['stu_old_password']);


		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
			}
			else
			{
				if(rows['affectedRows'] == 1)
				{
					req.session.user['stu_password'] = args['stu_password'];
					error(0,"Success",res);
				}
				else
				{
					error(1,"Failed",res);
				}
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res)
	}
	return;
}

/*
  Name:Teacher_Check_Information 
  Args: 
	req:
		JSON :[ args] arguments of this query
			teacher_id 		: student to add score
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    appear the basic information of a teacher
*/

function Teacher_Check_Information (req,res,next)
{
	var query = "SELECT teacher_number,teacher_name,teacher_phone FROM teacher WHERE teacher_id = ?;";
	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'TEACHER')
		{
			error(402,"Login First",res);
			return;
		}

		var query_args = [];
		query_args.push(req.session.user['teacher_id']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
			}
			else if(rows.length == 1)
			{
				data(rows[0],res);
			}
			else
			{
				error(303,"No data avalible",res);					
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res)
	}
	return;
}

/*
  Name:Student_Find_Class
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_id 		: student to find class
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    find syudent's class
*/


function Student_Find_Class(req,res,next)
{
	var query = "SELECT class.class_name,class.grade FROM class WHERE class_id = ?;";
	 try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'STUDENT')
		{
			error(402,"Login First",res);
			return;
		}

		var query_args = [];
		query_args.push(req.session.user['class_id']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
			}
			else if(rows.length == 1)
			{
				data(rows[0],res);
			}
			else
			{
				error(303,"No data avalible",res);					
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res);
	}
	return;


}

/*
  Name:Teacher_Modify_Password 
  Args: 
	req:
		JSON :[ args] arguments of this query
			teacher_id 		: student to add score
			teacher_old_password 		: old password
			teacher_password 		: new password

	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    modify the password of a teacher
*/

function Teacher_Modify_Password (req,res,next)
{
	var query = "UPDATE teacher SET teacher_password = ? WHERE teacher_id = ? AND teacher_password = ?;";
	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'TEACHER')
		{
			error(402,"Login First",res);
			return;
		}
		if(typeof(args['teacher_old_password']) != 'string' 
			|| typeof(args['teacher_config_password']) != 'string'
			|| typeof(args['teacher_password']) != 'string' )
			{
				error(401,"Invalid Argument",res);
				return;		
		}

		

		var query_args = [];
		query_args.push(args['teacher_password']);
		query_args.push(req.session.user['teacher_id']);
		query_args.push(args['teacher_old_password']);


		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
			}
			else
			{
				if(rows['affectedRows'] == 1)
				{
					req.session.user['teacher_password'] = args['teacher_password'];
					error(0,"Success",res);
				}
				else
				{
					error(1,"Failed",res);
				}
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res)
	}
	return;
}



/*
  Name:Teacher_Modify_Information 
  Args: 
	req:
		JSON :[ args] arguments of this query
			teacher_id 		: student to add score
			teacher_phone 		: new phone number
			teacher_number 		: new number

	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    modify the information of a teacher
*/

function Teacher_Modify_Information (req,res,next)
{
	var query = "UPDATE teacher SET teacher_phone = ?,teacher_number = ?  WHERE teacher_id = ? ;";
	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'TEACHER')
		{
			error(402,"Login First",res);
			return;
		}

		if(typeof(args['teacher_phone']) != 'string'
		|| typeof(args['teacher_number']) != 'string' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}	
		var query_args = [];
		query_args.push(args['teacher_phone']);
		query_args.push(args['teacher_number']);
		query_args.push(req.session.user['teacher_id']);


		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				if(rows['affectedRows'] == 1)
				{
					req.session.user['teacher_phone'] = args['teacher_phone'];
					req.session.user['teacher_number'] = args['teacher_number'];
					error(0,"Success",res);
				}
				else
				{
					error(301,"Nothing changed",res);
				}

			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res);
	}
	return;
}



/*
  Name:Teacher_Find_Class
  Args: 
	req:
		JSON :[ args] arguments of this query

	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    find the class of a teacher
*/

function Teacher_Find_Class(req,res,next)
{
	var query = "SELECT t.class_id,t.teacher_class_year,t.teacher_class_semester,class.class_name,class.grade,`subject`.subject_name FROM (SELECT * FROM teach WHERE teacher_id = ?) t LEFT JOIN class ON t.class_id = class.class_id LEFT JOIN `subject` ON t.subject_id = `subject`.subject_id;"; 
    try
	{
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'TEACHER')
		{
			error(402,"Login First",res);
			return;
		}
		var query_args = [];
		query_args.push(req.session.user['teacher_id']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else if(rows.length > 0)
			{
				data(rows,res);
			}
			else
			{
				error(303,"No data avalible",res);
			}
			return;
		});
	}
	catch(err)
	{
		error(-1,err,res);
	}
	return;


}

/*
  Name:Teacher_Find_Class
  Args: 
	req:
		JSON :[ args] arguments of this query

	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    find the class of a teacher
*/

function Teacher_Find_Subject(req,res,nexts)
{
	var query = "SELECT t.teacher_class_year,t.teacher_class_semester,`subject`.subject_id,`subject`.subject_name FROM (SELECT * FROM teach WHERE teacher_id = 1 ) t LEFT JOIN `subject` ON t.subject_id = `subject`.subject_id;"; 
    try
	{
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'TEACHER')
		{
			error(402,"Login First",res);
			return;
		}
		var query_args = [];
		query_args.push(req.session.user['teacher_id']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else if(rows.length > 0)
			{
				data(rows,res);
			}
			else
			{
				error(303,"No data avalible",res);
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res);
	}
	return;
}



/*
  Name:Parent_Check_Information 
  Args: 
	req:
		JSON :[ args] arguments of this query
			parent_id 		: student to add score
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    appear the basic information of a parent and his child
*/

function Parent_Check_Information (req,res,next)
{
	var query = "SELECT student.stu_name, student.stu_number,p.parent_phone FROM (SELECT * FROM parent  WHERE parent.parent_id = ?)p LEFT JOIN student ON student.parent_id = p.parent_id;";
	try
	{
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'PARENT')
		{
			error(402,"Login First",res);
			return;
		}

		var query_args = [];
		query_args.push(req.session.user['parent_id']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else if(rows.length == 1)
			{
				data(rows[0],res);
			}
			else
			{
				error(303,"No data avalible",res);
			}
			return;
		});
	}
	catch(err)
	{
		error(-1,err,res)
	}
	return;
}


/*
  Name:Parent_Modify_Password 
  Args: 
	req:
		JSON :[ args] arguments of this query
			teacher_id 		: student to add score
			teacher_old_password 		: old password
			teacher_password 		: new password

	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    modify the password of a parent
*/

function Parent_Modify_Password (req,res,next)
{
	var query = "UPDATE parent SET parent_password = ? WHERE parent_id = ? AND parent_password = ?;";
	try
	{
		var args = BeforeAspect(req.body);
		if(typeof(req.session.user) !=  'object' || 
			req.session.user_type != 'PARENT')
		{
			error(402,"Login First",res);
			return;
		}
		if(typeof(args['parent_config_password']) != 'string'
		|| typeof(args['parent_old_password']) != 'string' 
		|| typeof(args['parent_password']) != 'string' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}

		if(args['parent_password'] != args['parent_config_password'])
		{
			error(202,"Wrong config_password",res);
			return;
		}

		var query_args = [];
		query_args.push(args['parent_password']);
		query_args.push(req.session.user['parent_id']);
		query_args.push(args['parent_old_password']);


		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
			}
			else
			{
				if(rows['affectedRows'] == 1)
				{
					req.session.user['parent_password'] = args['parent_password'];
					return error(0,"Sucess",res);
				}
				return error(1,"Failed",res);
			}
			return;
		});

	}
	catch(err)
	{
		error(-1,err,res)
	}
	return;
}

/*
  Name:Parent_Modify_Information 
  Args: 
	req:
		JSON :[ args] arguments of this query
			teacher_id 		: student to add score
			teacher_phone 		: new phone number
			teacher_number 		: new number

	res: response to write data/error
	next:
  Return: 
  	None
  Description:
    modify the information of a Parent
*/

function Parent_Modify_Information (req,res,next)
{
	var query = "UPDATE parent SET parent_phone = ? WHERE parent_id = ?;";
	try
	{
        var args = BeforeAspect(req.body);
        if(typeof(req.session.user) !=  'object' 
		|| req.session.user_type != 'PARENT')
		{
			error(402,"Login First",res);
			return;
		}

		if(typeof(args['parent_phone']) != 'string' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		var query_args = [];	
		query_args.push(args['parent_phone']);
		query_args.push(req.session.user['parent_id']);


		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);

			}
			else
			{
				if(rows['affectedRows'] == 1)
				{
					req.session.user['parent_phone'] = args['parent_phone'];
					return error(0,"Sucess",res);
				}
				return error(1,"Failed",res);
			}
			return;
		});
	}
	catch(err)
	{
		error(-1,err,res);
	}
	return;
}

//Register '/' GET router
router.get('/', function(req, res, next) 
{
  data({},res);
});

//Register all routers 
var functions = {	"/Student_Check_Information" : Student_Check_Information
			,"/Student_Modify_Password"	: Student_Modify_Password
			,"/Student_Find_Class"	: Student_Find_Class
			,"/Teacher_Check_Information": Teacher_Check_Information
			,"/Teacher_Modify_Password" : Teacher_Modify_Password
			,"/Teacher_Modify_Information" : Teacher_Modify_Information
			,"/Teacher_Find_Class" : Teacher_Find_Class
			,"/Teacher_Find_Subject" : Teacher_Find_Subject
			,"/Parent_Check_Information" : Parent_Check_Information				
			,"/parent_Modify_Password" : Parent_Modify_Password
			,"/Parent_Modify_Information" : Parent_Modify_Information 
			}

for(var i in functions) 
{
	console.log("FUNCTION_LOADED(common):"+i);
	router.post(i, functions[i]);
}

module.exports = router;
